<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/22
 * Time: 10:59
 */

namespace app\index\model;

use think\Db;
use think\facade\Request;
use think\Model;

class User extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 登录获取ip和登录时间
     * @param $id
     * @return bool
     */
    static public function login($id)
    {
        $model = self::get($id);
        $model->last_login_ip = Request::ip(); //ip地址
        $model->last_login_time = time();  //登录时间
        $model->save();
        return true;
    }

    /**
     * 修改最后登录ip
     * @param $data
     * @return bool
     */
    static public function updateIp($data)
    {
        $data["last_login_ip"] = Request::ip();
        $data["last_login_time"] = time();
        self::where("name", $data["name"])->update([
            "last_login_ip" => $data["last_login_ip"],
            "last_login_time" => $data["last_login_time"],
        ]);
        return true;
    }

    /**
     * 获取用户详情
     * @param $id
     * @return array
     */
    public static function getUserInfo($id)
    {
        $data =  Db::table("user_role_relation")->where("user_id",$id)->column("role_id");
        $data =  Db::table("role_choose_relation")->whereIn("role_id",$data)->column("choose_id");
        $keys = "";
        foreach ($data as $key  => $value) {
            $keys .= $value .",";
        }
        $keys = substr($keys,0,-1);
        $data = array_unique(explode(",",$keys));

        $data =  Db::table("choose")->whereIn("id",$data)->column("name");
        return $data;
    }

    /**
     * 一对多
     * @return \think\model\relation\BelongsToMany
     */
    public function getRoleId()
    {
        return $this->belongsToMany("Role","user_role_relation","role_id","user_id");
    }
}